package Endian;

use Config;

use constant {
  Big => 1,
  Little => 2,
  Other => 3,
};

sub get_endian {
  my $byteorder = $Config{byteorder};
  return Little if( $byteorder == 1234 || $byteorder == 12345678 );
  return Big if( $byteorder == 4321 || $byteorder == 87654321 );
  die "Endian not supported (byteorder = $byteorder)\n";
  return Other;
}

sub swap_u16 {
  my $u16 = shift;
  $u16 = $u16 & 0xffff;
  $u16 = (($u16>>8) | ($u16<<8));
  return ($u16 & 0xffff);
}

sub swap_u32 {
  my $u32 = shift;
  $u32 = $u32 & 0xffffffff;
  $u32 = swap_u16($u32>>16) | (swap_u16($u32)<<16);
  return ($u32 & 0xffffffff);
}

sub le32toh {
  my $ret = shift;
  if(get_endian() == Big) {
    $ret = swap_u32($ret);
  }
  return $ret;
}

sub be32toh {
  my $ret = shift;
  if(get_endian() == Little) {
    $ret = swap_u32($ret);
  }
  return $ret;
}

sub le16toh {
  my $ret = shift;
  if(get_endian() == Big) {
    $ret = swap_u16($ret);
  }
  return $ret;
}

sub be16toh {
  my $ret = shift;
  if(get_endian() == Little) {
    $ret = swap_u16($ret);
  }
  return $ret;
}

1;
